import { queryFacAndClassList } from "@/api/common";
import { getSubSystemUserInfo } from "@/api/user";
import { useUpdateIsNeedBottomFooter, useUpdateViceMenu } from "@/hooks/useCommon";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useRouterStoreHook } from "@/store/modules/router";
import { type DataInfo, multipleTabsKey, setToken, userKey } from "@/utils/auth";
import { logout } from "@/utils/logout";
import NProgress from "@/utils/progress";
import "@/utils/sso";
import { buildHierarchyTree } from "@/utils/tree";
import { getQueryMap, isAllEmpty, isUrl, openLink, storageLocal } from "@pureadmin/utils";
import Cookies from "js-cookie";
import { PxMessage } from "px-ui";
import { createRouter, type RouteComponent, type Router, type RouteRecordRaw } from "vue-router";
import remainingRouter from "./modules/remaining";
import {
  ascending,
  findRouteByPath,
  formatFlatteningRoutes,
  formatTwoStageRoutes,
  getHistoryMode,
  getTopMenu,
  handleAliveRoute,
  initRouter,
  isOneOfArray
} from "./utils";

/** 自动导入全部静态路由，无需再手动引入！匹配 src/router/modules 目录（任何嵌套级别）中具有 .ts 扩展名的所有文件，除了 remaining.ts 文件
 * 如何匹配所有文件请看：https://github.com/mrmlnc/fast-glob#basic-syntax
 * 如何排除文件请看：https://cn.vitejs.dev/guide/features.html#negative-patterns
 */
const modules: Record<string, any> = import.meta.glob(
  // ["./modules/**/*.ts", "!./modules/**/remaining.ts"],
  [
    "./modules/**/error.ts"
    // "./modules/**/home.ts"
    // "./modules/**/nested.ts",
    // "!./modules/**/remaining.ts"
  ],
  {
    eager: true
  }
);

/** 原始静态路由（未做任何处理） */
const routes = [];

Object.keys(modules).forEach(key => {
  routes.push(modules[key].default);
});

/** 导出处理后的静态路由（三级及以上的路由全部拍成二级） */
export const constantRoutes: Array<RouteRecordRaw> = formatTwoStageRoutes(
  formatFlatteningRoutes(buildHierarchyTree(ascending(routes.flat(Infinity))))
);

/** 用于渲染菜单，保持原始层级 */
export const constantMenus: Array<RouteComponent> = ascending(routes.flat(Infinity)).concat(...remainingRouter);

/** 不参与菜单的路由 */
export const remainingPaths = Object.keys(remainingRouter).map(v => {
  return remainingRouter[v].path;
});

/** 默认路由（无需从接口获取） */
export const defaultRoutes = () => constantRoutes.concat(...(remainingRouter as any));

/** 创建路由实例 */
export const router: Router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_HISTORY),
  routes: defaultRoutes(),
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  }
});

/** 重置路由 */
export function resetRouter() {
  router.getRoutes().forEach(route => {
    const { name, meta } = route;
    if (name && router.hasRoute(name) && meta?.backstage) {
      router.removeRoute(name);
    }
  });
  router.options.routes = formatFlatteningRoutes(defaultRoutes());
  usePermissionStoreHook().clearAllCachePage();
}

/** 路由白名单 */
const whiteList = [
  "/fullScreen/gas/operation/topology/specificGas/chlorine",
  "/fullScreen/machine/operation/topology/createReplaceFilter",
  "/fullScreen/water/water/topology/controlValue",
  "/fullScreen/fab/topology/tooltip/specificGas/chlorine"
];

const { VITE_HIDE_HOME } = import.meta.env;

router.beforeEach(async (to: ToRouteType, _from, next) => {
  // 更新副路由
  await useUpdateViceMenu(to);
  // 判断当前页面是否需要底部按钮操作栏
  // 此处 如果需要自定义底部按钮栏的显示隐藏，可在进入路由前带上参数 custom 为非空时，会暂时隐藏底部按钮栏
  await useUpdateIsNeedBottomFooter();
  if (to.meta?.keepAlive) {
    handleAliveRoute(to, "add");
    // 页面整体刷新和点击标签页刷新
    if (_from.name === undefined || _from.name === "Redirect") {
      handleAliveRoute(to);
    }
  }
  const userInfo = storageLocal().getItem<DataInfo<number>>(userKey);
  NProgress.start();
  const externalLink = isUrl(to?.name as string);
  if (!externalLink) {
    to.matched.some(item => {
      if (!item.meta.title) return "";
    });
  }
  /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
  function toCorrectRoute() {
    whiteList.includes(to.path) ? next(_from.fullPath) : next();
    useMultiTagsStoreHook().sortTags(to);
  }
  // console.log(removeToken);
  if (Cookies.get(multipleTabsKey) && userInfo) {
    // 无权限跳转403页面
    if (to.meta?.roles && !isOneOfArray(to.meta?.roles, userInfo?.roles)) {
      next({ path: "/error/403" });
    }
    // 开启隐藏首页后在浏览器地址栏手动输入首页welcome路由则跳转到404页面
    if (VITE_HIDE_HOME === "true" && to.fullPath === "/welcome") {
      next({ path: "/error/404" });
    }
    if (_from?.name) {
      // name为超链接
      if (externalLink) {
        openLink(to?.name as string);
        NProgress.done();
      } else {
        toCorrectRoute();
      }
    } else {
      // 刷新
      if (usePermissionStoreHook().wholeMenus.length === 0 && to.path !== "/login") {
        initRouter().then((router: Router) => {
          if (!useMultiTagsStoreHook().getMultiTagsCache) {
            const { path } = to;
            const route = findRouteByPath(path, router.options.routes[0].children);
            getTopMenu(true);
            // query、params模式路由传参数的标签页不在此处处理
            if (route && route.meta?.title) {
              if (isAllEmpty(route.parentId) && route.meta?.backstage) {
                // 此处为动态顶级路由（目录）
                const { path, name, meta } = route.children[0];
                useMultiTagsStoreHook().handleTags("push", {
                  path,
                  name,
                  meta
                });
              } else {
                const { path, name, meta } = route;
                useMultiTagsStoreHook().handleTags("push", {
                  path,
                  name,
                  meta
                });
              }
            }
          }
          // 确保动态路由完全加入路由列表并且不影响静态路由（注意：动态路由刷新时router.beforeEach可能会触发两次，第一次触发动态路由还未完全添加，第二次动态路由才完全添加到路由列表，如果需要在router.beforeEach做一些判断可以在to.name存在的条件下去判断，这样就只会触发一次）
          if (isAllEmpty(to.name)) router.push(to.fullPath);
        });
      }
      toCorrectRoute();
    }
  } else {
    const query = getQueryMap(window.location.href);
    console.log(query);
    const { ticket, token } = query as any;
    let headers = {
      "Content-Type": "application/json;"
    };
    if (token) {
      headers["authorization"] = `Bearer ${token}`;
    }
    if (ticket) {
      headers["ticket"] = ticket;
    }

    try {
      if (whiteList.includes(to?.path) && to?.fullPath !== "/login") {
        next();
        return;
      }
      const result = (await getSubSystemUserInfo({}, headers)) as any;
      if (result.menuList && result.menuList.length > 0) {
        const dynamicsMenuList = result.menuList.filter(item => item.sysCode === "sys-ifp");
        if (dynamicsMenuList && dynamicsMenuList.length > 0) {
          localStorage.setItem("permissionList", result.permissionList);
          localStorage.setItem("userInfo", JSON.stringify(result.user));
          // 获取后端路由
          return initRouter(dynamicsMenuList).then(async () => {
            setToken({ token });
            // 调用获取厂区接口，存储facCode
            const list = await queryFacAndClassList();
            if (list["FACTORY"] && list["FACTORY"].length === 0) {
              PxMessage.error({
                message: "暂无厂区权限，请联系管理员！",
                onClose: () => {
                  logout();
                },

                duration: 2000
              });
              return;
            }
            router.push(getTopMenu(true).path);
            PxMessage.success("登录成功！");
            // 获取当前登录用户在pms的权限
            const pmsPermission = await getSubSystemUserInfo({ sysCode: "sys-pms" });
            localStorage.setItem("pmsPermission", JSON.stringify(pmsPermission?.permissionList || []));
            localStorage.setItem("facCode", list["FACTORY"][0].code);
            localStorage.setItem("facList", JSON.stringify(list["FACTORY"]));
            if (list["CLASS"] && list["CLASS"].length === 1 && !list["CLASS"][0].code) {
              localStorage.setItem("classList", JSON.stringify([]));
            } else {
              localStorage.setItem("classList", JSON.stringify(list["CLASS"]));
            }
            localStorage.setItem("hseFacAreaList", JSON.stringify(list["HSE-AREA"]));
            next({ path: "/all" });
          });
        } else {
          PxMessage.error({
            message: "暂无权限，请联系管理员！",
            onClose: () => {
              logout();
            },

            duration: 2000
          });
        }
      } else {
        PxMessage.error({
          message: "暂无权限，请联系管理员！",
          onClose: () => {
            logout();
          },
          duration: 2000
        });
      }
    } catch (e) {
      console.error(e);
      next();
    }
  }
});

router.afterEach(() => {
  useRouterStoreHook().SET_SUBJECT();
  NProgress.done();
});

export default router;
